package com.wnhz.work.yz;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wnhz.work.yz.activity.LoginFirstActivity;
import com.wnhz.work.yz.activity.SettingActivity;
import com.wnhz.work.yz.bean.BathroomDetailBean;
import com.wnhz.work.yz.bean.Fragment4Bean;
import com.wnhz.work.yz.bean.UserBean;
import com.wnhz.work.yz.bean.VersionBean;
import com.wnhz.work.yz.constant.Constants;
import com.wnhz.work.yz.dialog.SimpleDialog;
import com.wnhz.work.yz.fragment.HomeFragment1;
import com.wnhz.work.yz.fragment.HomeFragment2;
import com.wnhz.work.yz.fragment.HomeFragment3;
import com.wnhz.work.yz.fragment.HomeFragment4;
import com.wnhz.work.yz.utils.BroadCastReceiverUtil;
import com.wnhz.work.yz.utils.IntentUtils;
import com.wnhz.work.yz.utils.SystemUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

public class  MainActivity extends BaseActivity implements View.OnClickListener, BroadCastReceiverUtil.OnReceiveBroadcast  {

    public static boolean isForeground = true;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 667;
    private static final int REQUEST_CODE = 668;
    private HomeFragment1 fragment1;
    private HomeFragment2 fragment2;
    private HomeFragment3 fragment3;
    private HomeFragment4 fragment4;

    private List<Fragment> fragmentList;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private RelativeLayout layout1, layout2, layout3, layout4;
    private ImageView image1, image2, image3, image4;
    private TextView text1, text2, text3, text4;

    private int textColorNor, textColorCli;
    private int position;

    private int[] bottomImgNor = {R.mipmap.ic_home2_nor, R.mipmap.ic_gouwuche_nor, R.mipmap.ic_faxian_nor, R.mipmap.ic_mine_nor};
    private int[] bottomImgCli = {R.mipmap.ic_home2_li, R.mipmap.ic_gouwuche_li, R.mipmap.ic_faxian_li, R.mipmap.ic_mine_li};

    private List<ImageView> images = new ArrayList<>();
    private List<TextView> textViews = new ArrayList<>();

    private String phone;
    private String passWord;
    private boolean haveYuShou;
    private SimpleDialog dialog;
    private String message;
    private Activity activity;
    BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        if (MyApplication.getInstance().window_w == -1) {
            WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            MyApplication.getInstance().window_w = wm.getDefaultDisplay().getWidth();
            MyApplication.getInstance().window_h = wm.getDefaultDisplay().getHeight();
        }
        //检查版本更新
        checkUpdate();

        upLoad();
        initData();
        initView();
        broadcastReceiver  = BroadCastReceiverUtil.registerBroadcastReceiver(this, new String[]{ Constants.LOGO_SUCCESS}, this);
    }

    private void checkUpdate() {
        Map<String, Object> map = new HashMap<>();
        XUtil.Post(Url.UPDATE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("=====版本升级更新=====", result);
                Gson gson = new Gson();
                VersionBean versionBean = gson.fromJson(result, VersionBean.class);
                if (versionBean.getResult().equals("1")) {
                    Log.e("=====当前版本=====", "" + SystemUtils.getVersionCode(MainActivity.this));
                    if (versionBean.getInfo().getIs_update().equals("1")) {
                        if (Integer.valueOf(versionBean.getInfo().getVersionCode()) > SystemUtils.getVersionCode(MainActivity.this)) {
                            dialog = new SimpleDialog(MainActivity.this, "检测到有新版本", "退出", "更新", new SimpleDialog.OnButtonClick() {
                                @Override
                                public void onNegBtnClick() {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("token", MyApplication.getInstance().getUserBean().getToken());
                                    XUtil.Post(Url.MEMBER_LOGOUT, map, new MyCallBack<String>() {
                                        @Override
                                        public void onSuccess(String result) {

                                            super.onSuccess(result);
                                            Log.e("退出登录", "onSuccess: out= " + result);
                                            try {
                                                JSONObject jsonObject = new JSONObject(result);
                                                String str = jsonObject.getString("result");
                                                message = jsonObject.optString("message");
                                                if ("1".equals(str)) {
                                                    SharedPreferences sp = getSharedPreferences("login", 0);
                                                    sp.edit().clear().commit();
                                                    message = "退出成功";
                                                    MyApplication.getInstance().userBean = null;
                                                    MyApplication.getInstance().exit(activity);

                                                } else {

                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }

                                        @Override
                                        public void onFinished() {
                                            if ("退出成功".equals(message))
                                                Toast.makeText(MainActivity.this, "" + message, Toast.LENGTH_SHORT).show();
                                            super.onFinished();
                                        }

                                        @Override
                                        public void onError(Throwable ex, boolean isOnCallback) {
                                            super.onError(ex, isOnCallback);
                                        }
                                    });
                                }

                                @Override
                                public void onPosBtnClick() {
                                    //跳转下载链接地址
                                    IntentUtils.openBrowser(MainActivity.this, "http://a.app.qq.com/o/simple.jsp?pkgname=com.wnhz.work.yz");
                                }
                            });
                            dialog.show();
                        }
                    } else if (versionBean.getInfo().getIs_update().equals("0")) {
                        if (Integer.valueOf(versionBean.getInfo().getVersionCode()) > SystemUtils.getVersionCode(MainActivity.this)) {
                            dialog = new SimpleDialog(MainActivity.this, "检测到有新版本", "朕知道了", "更新", new SimpleDialog.OnButtonClick() {
                                @Override
                                public void onNegBtnClick() {
                                    dialog.dismiss();
                                }

                                @Override
                                public void onPosBtnClick() {
                                    IntentUtils.openBrowser(MainActivity.this, "http://a.app.qq.com/o/simple.jsp?pkgname=com.wnhz.work.yz");
                                }
                            });
                            dialog.show();
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BathroomDetailBean event) {

        flag = true;
    }

    private boolean flag;

    @Override
    protected void onResume() {

        if (flag == true) {
            if (MyApplication.getInstance().getUserBean() != null) {
                hideFragment(1);
            } else {
                startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
            }
        }

        super.onResume();
    }

    @Override
    protected void onPause() {
        flag = false;
        super.onPause();
    }

    private void upLoad() {
        String registrationID = JPushInterface.getRegistrationID(getBaseContext());
        Log.e("极光registrationID", registrationID);
        SharedPreferences sp = getSharedPreferences("login", 0);
        phone = sp.getString("phone", "");
        passWord = sp.getString("password", "");
        Map<String, Object> map = new Hashtable<>();
        map.put("phone", phone);
        map.put("password", passWord);
        map.put("chat_id", registrationID);

        XUtil.Post(Url.USER_LOGIN, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    Log.e("222---", result);
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");

                    if ("1".equals(res)) {
                        String message = jsonObject.optString("message");
                        String token = jsonObject.optString("token");
                        String url = jsonObject.optString("url");
                        String is_c = jsonObject.optString("is_c");
                        String area = jsonObject.optString("area");
                        String ratio = jsonObject.optString("ratio");
                        //
                        UserBean bean = new UserBean();
                        bean.setPhone(phone);
                        bean.setPassWord(passWord);
                        bean.setToken(token);
                        bean.setHeadUrl(url);
                        bean.setArea(area);
                        bean.setIs_c(is_c);
                        bean.setRatio(ratio);
                        MyApplication.getInstance().userBean = bean;
                    } else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                upLoad2();
                Log.e("222---", "asdasdasd");
                closeDialog();
            }
        });

    }

    private void upLoad2() {
        if (MyApplication.getInstance().getUserBean() == null) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        XUtil.Post(Url.MEMBER_GETUSERINFO, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                Fragment4Bean bean = new Fragment4Bean();
                Gson gson = new Gson();
                bean = gson.fromJson(result, Fragment4Bean.class);
                MyApplication.getInstance().getUserBean().setUserName(bean.getRealname());
                MyApplication.getInstance().getUserBean().setClassName(bean.getClassname());
                MyApplication.getInstance().getUserBean().setHeadLogo(bean.getPerson_img());
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }


    private void initData() {
        textColorNor = getResources().getColor(R.color.text_two);
        textColorCli = getResources().getColor(R.color.main_color);
    }

    public List<View> tab_lay = new ArrayList<>();

    private void initView() {
        layout1 = (RelativeLayout) findViewById(R.id.tab1);
        layout2 = (RelativeLayout) findViewById(R.id.tab2);
        layout3 = (RelativeLayout) findViewById(R.id.tab3);
        layout4 = (RelativeLayout) findViewById(R.id.tab4);
        tab_lay.add(layout1);
        tab_lay.add(layout2);
        tab_lay.add(layout3);
        tab_lay.add(layout4);

        image1 = (ImageView) findViewById(R.id.main_image1);
        image2 = (ImageView) findViewById(R.id.main_image2);
        image3 = (ImageView) findViewById(R.id.main_image3);
        image4 = (ImageView) findViewById(R.id.main_image4);
        images.add(image1);
        images.add(image2);
        images.add(image3);
        images.add(image4);

        text1 = (TextView) findViewById(R.id.main_text1);
        text2 = (TextView) findViewById(R.id.main_text2);
        text3 = (TextView) findViewById(R.id.main_text3);
        text4 = (TextView) findViewById(R.id.main_text4);
        textViews.add(text1);
        textViews.add(text2);
        textViews.add(text3);
        textViews.add(text4);

        layout1.setOnClickListener(this);
        layout2.setOnClickListener(this);
        layout3.setOnClickListener(this);
        layout4.setOnClickListener(this);

        fragmentList = new ArrayList<>();
        fragment1 = new HomeFragment1();
        fragment2 = new HomeFragment2();
        fragment3 = new HomeFragment3();
        fragment4 = new HomeFragment4();

        fragmentList.add(fragment1);
        fragmentList.add(fragment2);
        fragmentList.add(fragment3);
        fragmentList.add(fragment4);

        fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.main_content, fragment1);
        transaction.add(R.id.main_content, fragment2);
        transaction.add(R.id.main_content, fragment3);
        transaction.add(R.id.main_content, fragment4);

        transaction.hide(fragment2);
        transaction.hide(fragment3);
        transaction.hide(fragment4);

        transaction.commit();

        image1.setImageResource(bottomImgCli[0]);
        text1.setTextColor(textColorCli);
    }


    public void hideFragment(int index) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (i == index) {
                transaction.show(fragmentList.get(i));
                textViews.get(i).setTextColor(textColorCli);
                images.get(i).setImageResource(bottomImgCli[i]);
            } else {
                transaction.hide(fragmentList.get(i));
                textViews.get(i).setTextColor(textColorNor);
                images.get(i).setImageResource(bottomImgNor[i]);
            }

        }
        transaction.commit();
    }


    @Override
    public void onClick(View view) {
        Intent intent;
        //initBottomView();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (view.getId()) {
            case R.id.tab1:
                hideFragment(0);
                /*transaction.show(fragmentList.get(0)).commit();
                image1.setImageResource(bottomImgCli[0]);
                text1.setTextColor(textColorCli);*/
//                fragment1.scrollTop();
                break;

            case R.id.tab2:
                if (MyApplication.getInstance().getUserBean() != null) {
                    hideFragment(1);
                    /*transaction.show(fragmentList.get(3)).commit();
                    image4.setImageResource(bottomImgCli[3]);
                    text4.setTextColor(textColorCli);*/
                    fragment2.refresh();
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
                }
                /*transaction.show(fragmentList.get(1)).commit();
                image2.setImageResource(bottomImgCli[1]);
                text2.setTextColor(textColorCli);*/
//                fragment2.scrollTop();
                break;

            case R.id.tab3:
                hideFragment(2);
                /*transaction.show(fragmentList.get(2)).commit();
                image3.setImageResource(bottomImgCli[2]);
                text3.setTextColor(textColorCli);*/
                break;

            case R.id.tab4:
                if (MyApplication.getInstance().getUserBean() != null) {
                    if (MyApplication.getInstance().getUserBean().getToken() == null) {
                        startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
                    } else {
                        hideFragment(3);
                        fragment4.uphead();
                    }
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
                }
                break;

            default:
                break;
        }
    }

    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                // 退出代码
//                MyApplication.isLogin = false;
                finish();
                System.exit(0);
                System.runFinalizersOnExit(true);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        position = intent.getIntExtra("Pagination", 0);
        switch (position) {
            case 0:
                onClick(layout1);
                break;
            case 1:
                onClick(layout2);
                break;
            case 2:
                onClick(layout3);
                break;
            case 3:
                onClick(layout4);
                break;
            default:
                break;
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Constants.LOGO_SUCCESS)) {
            //检查版本更新
            checkUpdate();
            upLoad();
        }
    }
}
